﻿// For an introduction to the Page Control template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkId=232511
(function () {
    "use strict";

    WinJS.UI.Pages.define("/pages/main/main.html", {
        // This function is called whenever a user navigates to this page. It
        // populates the page elements with the app's data.
        ready: function (element, options) {
            this.setUpEvents();

            var h = $(document).height();
            $('#section-list').height(h);
            $('#section-detail').height(h);
            $('#to-top-floater').css({ 'margin-left': $(document).width() * 0.4 });

            if (options && options.queryText) {
                //从搜索界面导航至此
                var blogger = options.queryText.blogger;
                var name = options.queryText.author;
                var avatar = options.queryText.avatar;
                this.switchleftpanel(true, blogger, avatar, name);
            } else {

                this.loadPosts(this.curType);
            }

            var manager = Windows.ApplicationModel.DataTransfer.DataTransferManager.getForCurrentView();
            manager.addEventListener('datarequested', this.shareHandler);
        },

        unload: function () {
            var manager = Windows.ApplicationModel.DataTransfer.DataTransferManager.getForCurrentView();
            manager.removeEventListener('datarequested', this.shareHandler);
        },
        switchleftpanel: function (showblogger, blogger, avater, title) {
            var menu = $('#section-menu'), blog = $('#section-blogger'), self = this;
            if (showblogger) {
                blog.show();
                menu.hide();
                self.curType.type = 'blogger_home';
                self.curType.blogger = blogger;
                self.curType.page = 1;
                self.loadPosts(self.curType);
                document.querySelector('#blogger_avater').src = avater;
                document.querySelector('#blogger_author').innerHTML = title;
            }
            else {
                blog.hide();
                menu.show();
                self.curMenu = -1;
            }
        },
        updateLayout: function (element, viewState, lastViewState) {
            /// <param name="element" domElement="true" />

            // TODO: Respond to changes in viewState.
        },
        isloading: false,
        //当前菜单索引
        curMenu: 0,
        curType: {
            page: 1,
            type: 'blog_home'
        },
        curPost: {
            post_id: 0,
            page: 1,
            pagesize: 30,
            title: "",
            author: "",
            pub_date: "",
        },
        //初始化事件：menu点击事件、timeline点击事件
        setUpEvents: function () {
            var self = this,
            $menus = $('#id_menu').children();

            //setup menus events
            $menus.on('click', function () {
                var $el = $(this),
                    idx = $el.index();
                if (idx == self.curMenu) {
                    return;
                }
                self.curMenu = idx;
                var item = $el.find('a');
                if (item && item.length) {
                    var type = item[0].href.split('#')[1];
                    $menus.removeClass('menu-current').eq(self.curMenu).addClass('menu-current');
                    self.curType.type = type;
                    self.curType.page = 1;
                    self.loadPosts(self.curType);
                }
            });

            //setup timeline item click event
            $('#mainframe').click(function (evt) {
                var target = evt.target,
                    cmd = target.getAttribute('data-cmd');
                if (cmd) {
                    switch (cmd) {
                        case "view-detail":
                            var $item = $(target);

                            //add selected class
                            $('#mainlist').children().removeClass('timeline-item-current');
                            if ($item.attr('class').indexOf('timeline-item')) {
                                $item.parent().addClass('timeline-item-current');
                                target = $item.parent()[0];
                            }
                            else {
                                $item.addClass('timeline-item-current');
                            }
                            self.loadPost(target);
                            break;
                        case "view-blogger":
                            var blogger = target.getAttribute('data-blogid');
                            var name = target.getAttribute('data-author');
                            var avatar = target.getAttribute('data-avatar');
                            self.switchleftpanel(true, blogger, avatar, name);
                            break;
                        case "view-comments":
                            var pid = target.getAttribute('data-pid');
                            break;
                        default:
                            break;
                    }
                }
            });

            $('#to-top-floater').click(function () {
                $('#section-list').animate({ scrollTop: 0 }, 300);
            });

            $(document).keydown(function (e) {
                var code = e.code || e.which;
                switch (code) {
                    case 39://向右箭头
                        //case 40://向下箭头
                    case 74://J

                        self.move(true);
                        break;
                    case 37://向左箭头
                        //case 38://向上箭头
                    case 75://K
                        self.move(false);
                        break;
                }
            });

            $('#section-list').scroll(function (e) {
                if (self.isloading) {
                    return;
                }
                var list = $('#section-list');
                var scrollTop = list.scrollTop(),
                    scrollHeight = list[0].scrollHeight,
                    listHeight = list.height();
                var differ = scrollTop + listHeight - scrollHeight;
                if (differ > -100) {
                    self.curType.page++;
                    self.loadPosts(self.curType);
                }
                //回到顶部是否可见
                if (scrollTop < 10) {
                    $('#to-top-floater').hide();
                }
                else {
                    $('#to-top-floater').show();
                }
            });

            $('#blogger_back').click(function () {
                self.switchleftpanel(false);
            });

            $('#detail-share').click(function () {
                Windows.ApplicationModel.DataTransfer.DataTransferManager.showShareUI();
            });

            $('#appbar_refresh').click(function () {
                self.clear();
                self.loadPosts(self.curType);
            });
        },
        //键盘快捷键移动
        move: function (isDown) {
            var next = undefined, self = this, _current = $('.timeline-item-current');
            next = isDown ? _current.next() : _current.prev();
            if (next && next.length === 1) {
                next.addClass('timeline-item-current');
                _current.removeClass('timeline-item-current');
                next[0].scrollIntoView();
                self.loadPost(next[0]);
            }
        },
        //加载不同类别时清空当前数据
        clear: function () {
            $('#mainlist').empty();
            $('#detail-content').empty();
            document.querySelector('#detail-title').textContent = '';
            document.querySelector('#detail-author').textContent = '';
        },
        //加载信息流数据
        loadPosts: function (post) {
            var self = this;
            if (self.isloading) {
                return;
            }
            self.isloading = true;
            $('#progressBar').css("display", "block");
            if (!post.pagesize) {
                post.pagesize = 30;
            }
            if (!post.page)
            {
                post.page = 1;
            }
            if (post.page == 1) {
                self.clear();
            }
            var url = "";
            switch (post.type) {
                case "blog_home":
                    url = 'http://wcf.open.cnblogs.com/blog/sitehome/paged/' + post.page + '/' + post.pagesize;
                    break;
                case "blog_foureight":
                    url = 'http://wcf.open.cnblogs.com/blog/48HoursTopViewPosts/50';
                    break;
                case "blog_ten":
                    url = 'http://wcf.open.cnblogs.com/blog/TenDaysTopDiggPosts/50';
                    break;
                case "blog_recommend":
                    url = 'http://wcf.open.cnblogs.com/blog/bloggers/recommend/' + post.page + '/' + post.pagesize;
                    break;
                case "news_recent":
                    url = 'http://wcf.open.cnblogs.com/news/recent/paged/' + post.page + '/' + post.pagesize;
                    break;
                case "news_hot":
                    url = 'http://wcf.open.cnblogs.com/news/hot/50';
                    break;
                case "news_recommend":
                    url = 'http://wcf.open.cnblogs.com/news/recommend/paged/' + post.page + '/' + post.pagesize;
                    break;
                case "blogger_home":
                    url = 'http://wcf.open.cnblogs.com/blog/u/' + post.blogger + '/posts/' + post.page + '/' + post.pagesize;
                    break;
                default:

            }

            WinJS.xhr({ "url": url }).done(
                function completed(result) {
                    self.isloading = false;
                    $('#progressBar').hide();
                    if (result.status == 200) {
                        try {
                            var data = $.xml2json(result.responseText);
                            //当前是什么摸板，是新闻摸板、博客摸板还是推荐博客摸板
                            var templateId = '';
                            if (post.type == 'blog_recommend') {
                                templateId = 'DT_Blogger';
                            }
                            else {
                                templateId = 'DT_PreviewList';
                            }

                            if (post.page == 1) {
                                $('#mainlist').append(template(templateId, data));

                                var first = $('#mainlist .timeline-item:first');
                                first.addClass('timeline-item-current');
                                if (first && first.length) {
                                    self.loadPost(first[0]);
                                }
                            }
                            else {
                                //append
                                $('#mainlist').append(template(templateId, data));
                            }

                        } catch (e) {
                            console.error("load timeline data error!");
                        }
                    }
                },
                function error(error) {
                    self.isloading = false;
                    $('#progressBar').css("display", "none");
                });
        },
        //加载博客详细内容
        loadPost: function (node) {
            var self = this, detail = $('#detail-content');
            var post = {
                post_id: node.getAttribute('data-qid'),
                author: '',
                pub_date: node.getAttribute('data-pdate'),
                title: $(node).find('.title').length && $(node).find('.title')[0].textContent,
            };
            //detail.scrollTop(0);
            detail.empty();
            //document.querySelector('#detail-title').textContent = post.title;
            //document.querySelector('#detail-author').textContent = post.author + post.pub_date;

            if (self.curMenu < 4) {
                WinJS.xhr({ "url": 'http://wcf.open.cnblogs.com/blog/post/body/' + post.post_id }).done(
                function completed(res) {
                    try {
                        var data = $.xml2json(res.responseText);
                        detail.append(window.toStaticHTML(data));
                    } catch (e) {

                    }

                }, function error(res) {
                    if (res) {

                    }
                });
            }
            else {
                WinJS.xhr({ "url": 'http://wcf.open.cnblogs.com/news/item/' + post.post_id }).done(
                function completed(res) {
                    try {
                        var data = $.xml2json(res.responseText);
                        detail.append(window.toStaticHTML(data.Content));
                    } catch (e) {

                    }

                }, function error(res) {
                    if (res) {

                    }
                });
            }

        },
        //加载博客评论列表
        loadComments: function (comment) {
            var url = 'http://wcf.open.cnblogs.com/blog/post/' + comment.post_id + '/comments/' + comment.page + '/' + comment.pagesize;
            WinJS.xhr({ "url": url }).done(
                function completed(res) {
                },
            function error(res) {
            });
        },
        shareHandler: function (e) {
            var request = e.request;
            request.data.properties.title = document.querySelector('.timeline-item-current .title').innerText;
            request.data.properties.description = '博客园分享';
            request.data.setText(document.querySelector('.timeline-item-current .summary').innerText);
        }
    });
})();
